var express = require('express');
var router = express.Router();
const tableName = 'cart'
const tableNameGoods = 'goods'
const { Success, MError } = require("../utils/Result");
const Db = require("../utils/Db");

async function getSpecsBySn(req, sn) {
    const [attrs] = await Db.select(req, `select * from specs_attr where id=${sn}`);
    return attrs.specsval;
}
//添加商品数据到购物车
router.post("/cartadd", async (req, res) => {
    let { uid, goodsid, num, sku_id, s1, s2, } = req.body;
    // 规格属性id
    if (!uid || !goodsid || !num || !sku_id || !s1) {
        res.send(MError("缺少必要条件")); return;
    }
    // 查询购物车
    let sql = `SELECT * FROM ${tableName} WHERE uid = '${uid}' AND goodsid = ${goodsid}`;
    // 查询规格属性
    let attrs = [];
    if (s1) {
        const s1Info = await getSpecsBySn(req, s1);
        attrs.push(s1Info);
    }
    if (s2) {
        const s2Info = await getSpecsBySn(req, s2);
        attrs.push(s2Info);
    }
    attrs = attrs.join(',');
    sql += ` AND attrs='${attrs}' `;
    const info = await Db.select(req, sql);
    let result;
    if (info) {
        //更新数量
        result = await Db.update(req, tableName, { num: parseInt(num) + info[0].num }, ` WHERE id = ${info[0].id}`);
    } else {
        // 查询sku价格
        const sku = await Db.select(req, `select * from goods_sku where id=${sku_id}`);
        // sku价格和名称
        const { price } = sku[0];
        const cartData = {
            uid, goodsid, num, s1, sku_id, attrs, price, status: 1
        }
        if (s2) {
            cartData.s2 = s2;
        }
        result = await Db.insert(req, tableName, cartData);
    }

    // 查询该用户下一共有几件商品（知识计算单品）用于购物车角标展示
    const cartCount = await Db.select(req, `SELECT count(id) as count FROM ${tableName} WHERE uid = '${uid}'`);

    if (result) {
        res.send(Success({ cartCount: cartCount[0].count }, "添加成功"));
    } else {
        res.send(MError("添加失败，请查看字段信息是否正确"));
    }
});


//获取购物车列表
router.get("/cartlist", async (req, res) => {
    const { uid } = req['query'];
    if (!uid) {
        res.send(MError("缺少必要条件")); return;
    }
    let sql = `SELECT a.*,b.goodsname,b.img FROM ${tableName} a LEFT JOIN ${tableNameGoods} b ON a.goodsid = b.id `;
    sql += ` WHERE a.uid = '${uid}'`
    let data = await Db.select(req, sql);
    res.send(Success(data?data:[]));
});


//修改购物车商品数量
router.post("/cartedit", async (req, res) => {
    let { id, num, status } = req.body;
    if (!id || !num || status === undefined) {
        return res.send(MError("缺少必要条件"));
    }
    // 要更新的字段
    const data = { num, status };
    const result = await Db.update(req, tableName, data, ` WHERE id = ${id}`);
    result === true ? res.send(Success()) : res.send(MError(result));
});

//删除购物车商品
router.post("/cartdelete", async (req, res) => {
    let { id } = req.body;
    if (!id) {
        return res.send(MError("缺少必要条件"));
    } else {
        const result = await Db.delete(req, `DELETE FROM ${tableName} WHERE id = '${id}'`);
        if (result === true) {
            res.send(Success([], "删除成功"))
        } else {
            res.send(MError());
        }
    }
});


// 更新当前用户购物车中所有商品的选中状态
router.post('/cartUpdateAllChecked', async (req, res) => {
    const { uid, status } = req.body;
    console.log(uid, status);
    if (!uid || status === undefined) {
        return res.send(MError("缺少必要条件"));
    }
    const data = {
        status
    }
    const result = await Db.update(req, tableName, data, ` WHERE uid = '${uid}'`);
    if (result) {
        return res.send(Success([], "更新成功"))

    }
    res.send(MError("更新失败"));
});

// 导出
module.exports = router;

